package com.ronan.imweb.controller;

import cn.hutool.json.JSONUtil;
import com.ronan.common.pojo.SendMsgReq;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * FileName    : com.withufuture.imweb.controller
 * Description :
 *
 * @author : ronan
 * @version : 1.0
 * Create Date : 2021/3/23 16:28
 **/
@RestController
@RequestMapping(value = "/im/web/kafka")
public class KafkaDemoController {

    @Autowired
    private KafkaTemplate<String,Object> kafkaTemplate;

    /** 离线消息 topic */
    private static final String OFFLINE_MESSAGE = "OFFLINE_MESSAGE";


    /** 离线消息前缀+accid */
    private static final String OFFLINE_MESSAGE_PREFIX = "OFFLINE_MESSAGE-";

    @PostMapping(value = "/provider")
    public void providerOfflineMessages(@RequestBody @Validated SendMsgReq msg) {
        kafkaTemplate.send(OFFLINE_MESSAGE,OFFLINE_MESSAGE_PREFIX+msg.getTo(),msg);
    }

    @KafkaListener(topics = {OFFLINE_MESSAGE})
    public void customerOM(ConsumerRecord<?,?> record) {
        String str = String.valueOf(record.value());
        String key = String.valueOf(record.key());
        System.out.println("key = " + key);
        SendMsgReq bean = JSONUtil.toBean(str, SendMsgReq.class);
        System.out.println("bean = " + bean.toString());
    }
}
